package org.sky.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.sky.base.PageView;
import org.sky.model.Meal;
import org.sky.service.MealService;
import org.sky.vo.MealVO;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Time;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-10-23
 * Time: 下午8:16
 * To change this template use File | Settings | File Templates.
 */

@Component("meal")
@Scope("prototype")
public class MealAction extends MyActionSupport implements ModelDriven<MealVO> {

    private MealService mealService;
    private final MealVO mealVO = new MealVO();
    private Meal meal = new Meal();
    private List<Meal> meals = new ArrayList<Meal>();

    private final static Logger logger = Logger.getLogger(MealAction.class);

    private HttpServletRequest request = ServletActionContext.getRequest();
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final String username = userDetails.getUsername();

    //查看各种套餐价格
    @Override
    public String execute() throws Exception {
        /** 每页显示的结果数 **/
        int maxResult = 6;
        /** 封装的页面数据 **/
        PageView<Meal> pageView = new PageView<Meal>(maxResult,
                mealVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("mealId", "desc");
        pageView.setQueryResult(mealService.getScrollData(Meal.class, firstIndex, maxResult, orderBy));
        mealVO.setPageView(pageView);
        view = "/page/meal/AllMeal.jsp";
        return VIEW;
    }

    //查看某种套餐价格
    public String findSpecialMeal() throws Exception {
        if ("".equals(mealVO.getMealName()) || "".equals(mealVO.getHoliday()) || "".equals(mealVO.getBeginTime()) || "".equals(mealVO.getEndTime())) {
            mealVO.setResultMessage("<script>alert('请选择相关信息！');location.href='/page/meal/OneMeal.jsp';</script>");
            return ERROR;
        }

        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("mealName", mealVO.getMealName());
        params.put("holiday", mealVO.getHoliday());
        params.put("beginTime", Time.valueOf(mealVO.getBeginTime()));
        params.put("endTime", Time.valueOf(mealVO.getEndTime()));
        meal = (Meal) mealService.findSpecialObject(Meal.class, params);

        if (meal == null) {
            mealVO.setResultMessage("<script>alert('并无此套餐！');location.href='/page/meal/OneMeal.jsp';</script>");
            return ERROR;
        }

        mealVO.setMeal(meal);
        if (mealVO.getFlag() == 1) {
            view = "/page/meal/UpdateMeal.jsp";
            return VIEW;
        } else if (mealVO.getFlag() == 2) {
            view = "/page/meal/DeleteMeal.jsp";
            return VIEW;
        } else {
            view = "/page/meal/OneMeal.jsp";
            return VIEW;
        }
    }

    public String loadMeal() {
        meal = mealService.find(Meal.class, mealVO.getMealId());
        if (meal == null) {
            mealVO.setResultMessage("<script>alert('找不到改套餐！');location.href='Meal.action';</script>");
            return ERROR;
        }
        mealVO.setMeal(meal);
        view = "/page/meal/UpdateMeal.jsp";
        return VIEW;
    }

    //更新套餐信息
    public String updateMeal() throws Exception {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("mealName", mealVO.getMealName());
        params.put("holiday", mealVO.getHoliday());
        params.put("beginTime", Time.valueOf(mealVO.getBeginTime()));
        params.put("endTime", Time.valueOf(mealVO.getEndTime()));
        meal = (Meal) mealService.findSpecialObject(Meal.class, params);
        if (meal != null) {
            mealVO.setMealId(meal.getMealId());
            meal = copyDefaultMealInfo(meal, mealVO);
            mealService.update(meal);
            mealVO.setResultMessage("<script>alert('套餐信息更新成功！');location.href='Meal.action?mealId=" + meal.getMealId() + "';</script>");
            logger.trace("User:" + username + " update the meal(id:" + meal.getMealId() + ")");
            return SUCCESS;
        }
        mealVO.setResultMessage("<script>alert('找不到改套餐！');location.href='Meal.action';</script>");
        return ERROR;
    }

    //删除某个套餐
    public String deleteMeal() {
        mealService.delete(Meal.class, mealVO.getMealId());
        mealVO.setResultMessage("<script>alert('套餐信息删除成功！');location.href='Meal.action';</script>");
        logger.trace("User:" + username + " delete the meal(id:" + mealVO.getMealId() + ")");
        return SUCCESS;
    }

    //添加套餐
    public String addMeal() {
        if ("".equals(mealVO.getHoliday()) || "".equals(mealVO.getBeginTime()) || "".equals(mealVO.getEndTime()) || 0.0 == mealVO.getCoupleRoomPrice() || 0.0 == mealVO.getStandardRoomPrice() || 0.0 == mealVO.getMiddleRoomPrice() || 0.0 == mealVO.getBigRoomPrice() || 0.0 == mealVO.getVipRoomPrice()) {
            mealVO.setResultMessage("<script>alert('请填写完整相关信息！');location.href='/page/meal/AddMeal.jsp';</script>");
            return ERROR;
        }
        if (mealVO.getBeginTime().equals(mealVO.getEndTime())) {
            mealVO.setResultMessage("<script>alert('套餐开始时间和结束时间不能相同！');location.href='/page/meal/AddMeal.jsp';</script>");
            return ERROR;
        }
        System.out.println(mealVO.getStandardRoomPrice());
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("mealName", mealVO.getMealName());
        params.put("holiday", mealVO.getHoliday());
        params.put("beginTime", Time.valueOf(mealVO.getBeginTime()));
        params.put("endTime", Time.valueOf(mealVO.getEndTime()));
        meal = (Meal) mealService.findSpecialObject(Meal.class, params);

        if (meal != null) {
            mealVO.setResultMessage("<script>alert('此套餐已存在！');location.href='/page/meal/AddMeal.jsp';</script>");
            return ERROR;
        }
        mealService.save(copyDefaultMealInfo(new Meal(), mealVO));
        mealVO.setResultMessage("<script>alert('套餐信息添加成功！');location.href='Meal.action';</script>");
        logger.trace("User:" + username + " add the meal(id:" + mealVO.getMealId() + ")");
        return SUCCESS;
    }

    //查找特定放假价格
    public String findOneMealPrice() {
        if ("".equals(mealVO.getRoomStyle()) || "".equals(mealVO.getMealName()) || "".equals(mealVO.getHoliday()) || "".equals(mealVO.getBeginTime()) || "".equals(mealVO.getEndTime())) {
            mealVO.setResultMessage("<script>alert('请填写完整相关信息！');location.href='/page/meal/findMeal.jsp';</script>");
            return ERROR;
        }
        double money = mealService.findPriceByRoomStyleAndMeal(mealVO.getRoomStyle(), mealVO.getMealName(), mealVO.getHoliday(), Time.valueOf(mealVO.getBeginTime()), Time.valueOf(mealVO.getEndTime()));
        if (money != 0.0d) {
            mealVO.setMoney(money);
            view = "/page/meal/findMeal.jsp";
            return VIEW;
        } else {
            mealVO.setResultMessage("<script>alert('套餐信息不存在！');location.href='/page/meal/findMeal.jsp';</script>");
            return ERROR;
        }
    }

    //查询某房间类型在某个时段的价格
    public String setMealPrice() {
        if ("".equals(mealVO.getRoomStyle()) || "".equals(mealVO.getMealName()) || "".equals(mealVO.getHoliday()) || "".equals(mealVO.getBeginTime()) || "".equals(mealVO.getEndTime())) {
            mealVO.setResultMessage("<script>alert('请填写完整相关信息！');location.href='Meal!findRoomStylePrice.action?roomStyle=" + mealVO.getRoomStyle() + "';</script>");
            return ERROR;
        }
        boolean success = mealService.setPrice(mealVO.getRoomStyle(), mealVO.getMealName(), mealVO.getMoney(), mealVO.getHoliday(), Time.valueOf(mealVO.getBeginTime()), Time.valueOf(mealVO.getEndTime()));
        if (success) {
            mealVO.setResultMessage("<script>alert('价格修改成功！');location.href='Meal.action';</script>");
            logger.trace("User:" + username + " the meal(id:" + mealVO.getMealId() + ") price update!");
            return SUCCESS;
        }
        mealVO.setResultMessage("<script>alert('价格修改失败！');location.href='Meal!findRoomStylePrice.action?roomStyle=" + mealVO.getRoomStyle() + "';</script>");
        return ERROR;
    }

    //查询某种房间类型的价格
    public String findRoomStylePrice() {
        if ("".equals(mealVO.getRoomStyle())) {
            mealVO.setResultMessage("<script>alert('请填写完整相关信息！');location.href='/page/meal/findRoomStylePrice.jsp';</script>");
            return ERROR;
        }
        meals = mealService.findRoomStylePrice(mealVO.getRoomStyle());
        if (meals.size() <= 0) {
            mealVO.setResultMessage("<script>alert('并没有此类型的房间！');location.href='/page/meal/findRoomStylePrice.jsp';</script>");
            return ERROR;
        }

        mealVO.setMeals(meals);
        view = "/page/meal/findRoomStylePrice.jsp";
        return VIEW;
    }

    @Override
    public MealVO getModel() {
        return mealVO;
    }

    @Resource(name = "mealServiceImpl")
    public void setMealService(MealService mealService) {
        this.mealService = mealService;
    }

    private Meal copyDefaultMealInfo(Meal targetMeal, MealVO mealVO) {
        targetMeal.setMealId(mealVO.getMealId());
        targetMeal.setEndTime(Time.valueOf(mealVO.getEndTime()));
        targetMeal.setBeginTime(Time.valueOf(mealVO.getBeginTime()));
        targetMeal.setMealName(mealVO.getMealName());
        targetMeal.setCoupleRoomPrice(mealVO.getCoupleRoomPrice());
        targetMeal.setStandardRoomPrice(mealVO.getStandardRoomPrice());
        targetMeal.setMiddleRoomPrice(mealVO.getMiddleRoomPrice());
        targetMeal.setBigRoomPrice(mealVO.getBigRoomPrice());
        targetMeal.setVipRoomPrice(mealVO.getVipRoomPrice());
        targetMeal.setHoliday(mealVO.getHoliday());
        return targetMeal;
    }

}
